import * as turf from '@turf/turf'
import fs from 'fs'
// const fs = require('fs')

const readFile = (path) => {
    return new Promise((resolve, reject) => {
        fs.readFile(path, 'utf-8', (err, data) => {
            if (err) {
                reject(err)
            }

            const resData = JSON.parse(data)
            resolve(resData)
        })
    })
}


Promise.all([
    readFile('./guizhou/关岭布依族.json'),
    readFile('./guizhou/普定县.json'),
    readFile('./guizhou/西秀区.json'),
    readFile('./guizhou/镇宁布依族.json'),
    readFile('./guizhou/紫云苗族.json')
    // readFile('./data/maoM.json'),
    // readFile('./data/yangJ.json'),
    // readFile('./data/yunF.json'),
    // readFile('./data/zhanJ.json'),
]).then(res => {
    console.log(res)
    let result = []
    let arr = []

    for (let i = 0; i < res.length; i++) {
        let arr1 = []
        let item = res[i].features
        for (let j = 0; j < item.length; j++) {
            let geometry = item[j].geometry.coordinates
            for (let coord = 0; coord < geometry.length; coord++) {
                result.push(geometry[coord])
                arr1.push({
                    "type": "Feature",
                    "geometry": {
                        "type": "Polygon",
                        "coordinates": geometry[coord]
                    }
                })
            }
        }
        arr.push(...arr1)
    }

    // const flatResult = result.flat(2)

    // const multiPoint = turf.multiPoint(flatResult);
    // const endResult = turf.cleanCoords(multiPoint).geometry.coordinates;



    console.log(result)

    // const opt = {
    //     "type": "FeatureCollection",
    //     "features": [
    //         {
    //             "type": "Feature",
    //             "geometry": {
    //                 "type": "Polygon",
    //                 "coordinates": result
    //             }
    //         }
    //     ]
    // }
    const opt = {
        "type": "FeatureCollection",
        // "features": [
        //     {
        //         "type": "Feature",
        //         "geometry": {
        //             "type": "Polygon",
        //             "coordinates": result
        //         }
        //     }
        // ]
        "features": arr
    }

    const mergedFeatures = turf.dissolve(opt);
    console.log(mergedFeatures)


    fs.writeFileSync(`./guizhou/result.json`, JSON.stringify(mergedFeatures))
}).catch(err => {
    console.log(err)
})